package com.smileus.service;

import java.util.List;

import com.ibatis.common.util.Page;
import com.smileus.entity.ServiceRouter;
import com.smileus.util.EnvProperties;
import com.smileus.util.ReflectionUtil;

@SuppressWarnings("unchecked")
public class ServiceRouterService extends BaseService {
	/**
	 * 根据host,port,comDomain,sysDmomain信息，查询ServiceRouter list
	 * 
	 * @param curtRouter
	 * @return
	 */
	private static final String SERVICE_ROUTER_HQL = " from ServiceRouter sr where sr.comDomain =:comDomain and sr.sysDomain =:sysDomain and sr.serviceHost = :serviceHost and sr.servicePort =:servicePort and sr.serviceType=:serviceType ";

	public List<ServiceRouter> queryByServiceRouter(ServiceRouter serviceRouter) {
		return getHibernateDAO().queryByValueBean(ServiceRouter.class, SERVICE_ROUTER_HQL, serviceRouter);
	}

	/**
	 * 查询其他正在运行的服务
	 * 
	 * @return
	 */
	private static final String OTHER_RUNNING_HQL = " from ServiceRouter sr where sr.serviceStatus = 1 and sr.pubAddress != ?";

	public List<ServiceRouter> queryOtherRunningService(ServiceRouter serviceRouter) {
		return getHibernateDAO().queryByParam(ServiceRouter.class, OTHER_RUNNING_HQL, serviceRouter.getPubAddress());
	}

	/**
	 * 查询所有正在运行的服务
	 * 
	 * @return
	 */
	private static final String ALL_RUNNING_HQL = " from ServiceRouter sr where sr.serviceStatus = 1";

	public List<ServiceRouter> queryAllRunningService() {
		String serviceCentreSessionFactory = EnvProperties.getProperty("ServiceCentreSessionFactory");
		return getHibernateDAO(serviceCentreSessionFactory).queryByParam(ServiceRouter.class, ALL_RUNNING_HQL);
	}

	private static final String PUB_ADDDRESS_HQL = "from ServiceRouter sr where sr.pubAddress = ?";
	public ServiceRouter getServiceRouterByPubAddress(String pubAddress){
		List<ServiceRouter> list = getHibernateDAO().queryByParam(PUB_ADDDRESS_HQL, pubAddress);
		if (list == null || list.size() != 1) {
			throw new RuntimeException("Service_Router表基础数据有问题请检查pubAddress =" + pubAddress);
		}
		return list.get(0);
	}
	
	public void updateServiceStatus(String pubAddress, int serviceStatus) {
		ServiceRouter serviceRouter = getServiceRouterByPubAddress(pubAddress);
		serviceRouter.setServiceStatus(serviceStatus);
		getHibernateDAO().update(serviceRouter);
	}
	
	public ServiceRouter saveOrUpdateServiceRouter(ServiceRouter serviceRouter) {
		List<ServiceRouter> list = queryByServiceRouter(serviceRouter);
		if (list.size() == 0) {
			save(serviceRouter);
			return serviceRouter;
		}

		if (list.size() == 1) {
			ServiceRouter curtRouter = list.get(0);
			ReflectionUtil.copy(curtRouter, serviceRouter);
			update(curtRouter);
			return curtRouter;
		}

		throw new RuntimeException("表中配置数据存在问题，请检查：" + serviceRouter);
	}
	
	static String PAGE_HQL = " from ServiceRouter ";
	public Page<ServiceRouter> findPage(Page<ServiceRouter> page) {
		return findPageByArray(page, PAGE_HQL);
	}
}
